// pages/user/devide-status/device-status.ts
import Dialog from '@vant/weapp/dialog/dialog';
import userBaseInfoState from '../../../stores/userBaseInfo'
import Notify from '@vant/weapp/notify/notify'
import { bindDevice, bindXinyongDevice, unbindDevice, unbindXinyongDevice, syncDeviceDataApi, getXinyongTokenApi, getDeviceDataApi } from '../../../utils/api/patientDevice'

const testData = <PatientDeviceEntity>{
  deviceName: '测试设备',
  lastUpdateTime: '2024-08-01 09:10:11',
  deviceUid: 'B4:A7:38:2D:FC:21',
}

Page({

  data: {
    device: <PatientDeviceEntity | null>null,
    existDevice: false,
    showInputDialog: false,
    deviceUid: <string>'',
    brandOptionShow: false,
    brandOption: [
      '心永', '邮爱他'
    ],
    deviceBrand: '',
    showMeasurePreDialog: false,
    isMeasuring: false,
    showTips: false,
  },

  scanCodeEvent() {
    var that = this;
    wx.scanCode({
      success(res) {
        // 扫码成功后  在此处理接下来的逻辑
        // 设置设备号
        let deviceBrand = ''
        const deviceUid = res.result
        if (deviceUid.length == 15) {
          deviceBrand = '心永'
        } else {
          deviceBrand = '邮爱他'
        }
        that.setData({
          deviceBrand: deviceBrand,
          deviceUid: deviceUid,
        })
        that.lastConfirmBind();
      }
    })
  },
  inputCodeEvent() {
    this.setData({
      showInputDialog: true,
    })
  },
  brandOnClick() {
    this.setData({
      brandOptionShow: true,
    });
  },
  brandOnCancel() {
    this.setData({
      brandOptionShow: false,
    });
  },
  brandOnConfirm(event) {
    const { picker, value, index } = event.detail;
    this.setData({
      brandOptionShow: false,
      deviceBrand: value,
    })
    console.log("当前选择的品牌是" + this.data.deviceBrand)
  },
  changDeviceUid(event: any) {
    this.setData({
      deviceUid: event.detail,
    })
  },
  confirmInput() {
    if (this.data.deviceUid && this.data.deviceUid != '') {
      // 绑定设备
      this.setData({
        showInputDialog: false,
      })
      this.lastConfirmBind();
    }
  },

  // 定义格式化设备确认消息的函数
  formatDeviceMessage(deviceUid, deviceBrand) {
    return `绑定设备品牌: ${deviceBrand}\n绑定设备号: ${deviceUid}`;
  },

  // 二次校验绑定设备信息
  lastConfirmBind() {
    const that = this
    Dialog.confirm({
      message: this.formatDeviceMessage(this.data.deviceUid, this.data.deviceBrand)
    }).then(() => {
      // 定义不同厂商接口所需的数据内容
      const dataUaita = <PatientDeviceEntity>{
        deviceName: this.data.deviceBrand,
        deviceUid: this.data.deviceUid,
        patientUid: userBaseInfoState.data.patientUid,
      }
      const dataXinyong = {
        imei: this.data.deviceUid,
        uid: userBaseInfoState.data.patientUid
      }
      if (this.data.deviceBrand == '心永') {
        console.log('调用心永token刷新')
        // 接口成功后执行后续绑定逻辑
        bindXinyongDevice(dataXinyong)
          .then((res: any) => {
            console.log('心永设备绑定完成', res);
            Notify({ type: 'success', message: '绑定设备成功' });
            that.getDevice(); // 刷新设备列表
          })
          .catch((err: any) => {
            console.error('心永设备绑定失败', err);
            Notify({ type: 'danger', message: '设备绑定失败' });
          });
      } else {
        bindDevice(dataUaita).then((res: any) => {
          console.log('现在执行的是邮爱他的绑定接口')
          if (res.code == 1) {
            Notify({ type: 'danger', message: res.msg })
            return;
          }
          Notify({ type: 'success', message: '绑定设备成功' })
          // 获取该用户绑定设备信息
          that.getDevice()
        }).catch((err: any) => {
          console.log('调用绑定设备错误', err);
          Notify({ type: 'danger', message: '调用绑定设备错误' })
        })
      }
    })
  },

  cancelBind() {
    // 调用解除绑定API，成功后再调用下面取消存在
    const data = {
      deviceUid: this.data.deviceUid,
      patientUid: userBaseInfoState.data.patientUid,
    }
    const dataXinyong = {
      uid: userBaseInfoState.data.patientUid
    }
    if (this.data.device?.deviceBrand == 'xy') {
      unbindXinyongDevice(dataXinyong).then((res: any) => {
        Notify({ type: 'success', message: '解绑设备成功' })
        this.setData({
          device: null,
          existDevice: false,
          deviceUid: '',
        })
      }).catch((err: any) => {
        console.log('解绑设备错误', err);
        Notify({ type: 'danger', message: '解绑设备错误' })
      })
    } else {
      unbindDevice(data).then((res: any) => {
        Notify({ type: 'success', message: '解绑设备成功' })
        this.setData({
          device: null,
          existDevice: false,
          deviceUid: '',
        })
      }).catch((err: any) => {
        console.log('解绑邮爱他设备错误', err);
        Notify({ type: 'danger', message: '解绑设备错误' })
      })
    }

  },

  getDevice() {
    // 获取用户绑定设备
    const data = <PatientDeviceEntity>{
      patientUid: userBaseInfoState.data.patientUid,
    }
    getDeviceDataApi(data).then((res: any) => {
      //  取返回列表第一个作为第一个
      if (res.data == null || res.data.length == 0) {
        this.setData({
          existDevice: false,
          device: null
        })
        return;
      }
      const resData = res.data[0] as any;
      this.setData({
        existDevice: true,
        device: resData,
      })
      if (this.data.device?.deviceUid == null) {
        this.setData({
          existDevice: false,
          device: null
        })
        return;
      }
      console.log('现在的设备品牌是', this.data.device?.deviceBrand)
    }).catch((err: any) => {
      Notify({ type: 'danger', message: '获取已经绑定设备错误' })
      console.log('获取已经绑定设备错误', err);
    })
  },

  // 唤醒血压校准姿势提示
  measurePre() {
    this.setData({
      showMeasurePreDialog: true
    })
  },

  // 心永设备血压校准
  pressureDataCalibrationXinyong() {
    this.setData({
      showMeasurePreDialog: false,
      isMeasuring: true
    })
    const uid = userBaseInfoState.data.patientUid
    getXinyongTokenApi(uid).then((res: any) => {
      console.log(res)
      const tokenXy = res.data
      const wsUrl = `wss://open.heart-forever.com/api/ext/websocket/${tokenXy}`;
      
      // 保存WebSocket任务引用
      let webSocketTask = wx.connectSocket({
        url: wsUrl,
        header: {
          // 按需添加请求头
        },
        method: 'GET',
        success: (res) => {
          console.log('连接请求发送成功', res);
        },
        fail: (err) => {
          this.setData({ isMeasuring: false })
          console.error('连接请求失败', err);
          Notify({ type: 'danger', message: '连接校准服务器失败，请稍后重试' })
        }
      });
    
      // 关闭WebSocket的函数
      const closeWebSocket = () => {
        if (webSocketTask) {
          webSocketTask.close({
            code: 1000, // 正常关闭代码
            reason: '操作完成',
            success: () => {
              console.log('WebSocket已成功关闭');
              webSocketTask = null; // 清空引用
            },
            fail: (err) => {
              console.error('关闭WebSocket失败', err);
            }
          });
        }
      };
    
      wx.onSocketOpen((res) => {
        console.log('WebSocket连接已打开，可以发送消息', res);
        wx.sendSocketMessage({ data: JSON.stringify({ msgType: 'WABC' }) });
      });
    
      wx.onSocketMessage((res) => {
        console.log('收到服务器消息：', res);
        let messageData;
        try {
          messageData = JSON.parse(res.data);
        } catch (err) {
          console.error('消息解析失败（非JSON格式）', err);
          this.setData({ isMeasuring: false })
          Notify({ type: 'danger', message: '获取服务器信息错误' })
          closeWebSocket(); // 解析失败时关闭连接
          return;
        }
    
        const status = messageData.msgType
        const code = messageData.code
        const msg = messageData.msg
    
        // 处理手表不在线情况
        if ((status == 'WBBC') && (msg == '手表不在线')) {
          this.setData({ isMeasuring: false })
          Notify({ type: 'danger', message: '设备已离线，请检查设备是否开启' })
          closeWebSocket(); // 处理完成后关闭连接
          return;
        }
    
        // 处理校准结果
        if (status == 'WBCE') {
          this.setData({ isMeasuring: false });
          
          if (code == 0) {
            Notify({ type: 'success', message: '血压校准已完成' });
          } else if (code == 1) {
            Notify({ type: 'danger', message: '血压校准失败，请稍后再试' });
          } else if (code == 2) {
            Notify({ type: 'danger', message: '小程序掉线，标定失败' });
          } else if (code == 4) {
            Notify({ type: 'danger', message: '用户在手表上取消血压校准' });
          } else if (code == 5) {
            this.setData({ showTips: true });
            Notify({ type: 'danger', message: '示波法失败' });
          } else {
            this.setData({ showTips: true });
            Notify({ type: 'danger', message: '未知错误' });
          }
          
          closeWebSocket(); // 无论成功失败，处理完结果后关闭连接
          return;
        }
      });
    
      // 监听连接关闭事件
      wx.onSocketClose((res) => {
        console.log('WebSocket连接已关闭', res);
        webSocketTask = null;
      });
    
      // 监听连接错误事件
      wx.onSocketError((err) => {
        console.error('WebSocket错误', err);
        closeWebSocket(); // 发生错误时关闭连接
      });
    
    }).catch((err: any) => {
      console.log('获取心永token失败', err)
      this.setData({ isMeasuring: false })
      Notify({ type: 'danger', message: '获取已经绑定设备token错误' })
    });
    
  },

  // 展示提示校准方法完毕
  tipsShowed() {
    this.setData({showTips:false})
  },

  // 同步设备数据
  syncDeviceData() {
    const data = {
      deviceUid: this.data.device.deviceUid,
      patientUid: userBaseInfoState.data.patientUid,
    }
    const brand = this.data.device?.deviceBrand
    const that = this;
    if (brand == 'xy') {

    }
    else {
      syncDeviceDataApi(data).then((res: any) => {
        console.log('同步数据', res);
        if (res.code == 1) {
          Notify({ type: 'danger', message: res.msg })
          return;
        }
        Notify({ type: 'success', message: '同步设备数据成功' })
        that.getDevice()
      }).catch((err: any) => {
        Notify({ type: 'danger', message: '同步设备错误' })
        console.log('同步设备错误', err);
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // 获取数据
    // 临时示例数据用于预览样式，正式环境会调用 getDevice()
    this.setData({
      existDevice: true,
      device: Object.assign({}, testData, { deviceName: '元彬的 Apple Watch', battery: 30 })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})